package ngram_reader.viewer;

import ngram_reader.viewer.settings.SettingsDialog;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.prefs.Preferences;
import javax.swing.SwingWorker;
import main.Main;
import main.NGramWorker;
import ngram_reader.viewer.query.NGramSearchQuery;
import swingExtended.preferences.PreferenceGroup;
import swingExtended.progressPanel.ProgressPanelWorkerFactory;
import swingExtended.swingWorkers.GenericUpdateWorker;
import swingExtended.swingWorkers.ProgressUpdate;
import swingExtended.todoQueue.Task;

/**
 *
 * @author Shimu
 */
public class NGramSearchWindow extends javax.swing.JFrame {

    private final SettingsDialog SETTINGS_DIALOG;
    
    /** Creates new form NGramSearchWindow */
    public NGramSearchWindow() {
        initComponents();
        this.setLocationRelativeTo(this.getParent());

        // Get the preferences
        final PreferenceGroup PREF_GROUP = new PreferenceGroup(Preferences.userRoot().node(
                Main.USER_PREF_ROOT_NODE + "/" + this.getClass()));
        
        this.SETTINGS_DIALOG = new SettingsDialog(this, true);

        this.progressPanel.addWorkerFactory(new ProgressPanelWorkerFactory() {

            @Override
            public SwingWorker CreateWorker() {
                return new GenericUpdateWorker() {

                    @Override
                    protected void start() throws Exception {
                        if (!taskManager.hasItems()) {
                            throw new Exception("No items pending for search, you can add some from the \"Add Query\" tab");
                        }
                        progressPanel.getProgressBar().setMaximum(taskManager.getItemCount());
                        if (SETTINGS_DIALOG.clearOutputOnStart()) {
                            progressPanel.getAllTextPane().clearPane();
                            progressPanel.getErrorTextPane().clearPane();
                            progressPanel.getOutputTextPane().clearPane();
                            progressPanel.getStatusTextPane().clearPane();
                        }
                        
                    }

                    @Override
                    protected Object doInBackgroundHelper() throws Exception {
                        while (taskManager.hasItems()) {
                            Task<NGramSearchQuery> task = taskManager.getItem(0);
                            NGramSearchQuery searchQuery = task.getData();

                            final List<File> files = new ArrayList<>();
                            for (int i = NGramWorker.MIN_GRAM; i <= NGramWorker.MAX_GRAM; i++) {
                                if (searchQuery.withinGram(i)) {
                                    String url = SETTINGS_DIALOG.getNGramLocationPanel().getNGramLocation(i);
                                    files.add(new File(url));
                                }
                            }
                            NGramSearch_V2 search = new NGramSearch_V2(NGramSearchWindow.this.progressPanel,
                                    files, searchQuery, task.getProgressBar());
                            task.getProgressBar().start();
                            search.run();
                            search.get();
                            taskManager.removeItem(0);
                            publish(new ProgressUpdate() {

                                @Override
                                public void update() {
                                    progressPanel.getProgressBar().incrementValue(1);
                                }
                            });
                        }
                        return null;
                    }
                };
            }
        });
        this.addQueryPanel.setTaskManager(taskManager);
        this.loadQueryPanel.setTaskManager(taskManager);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        scrollPaneStack = new javax.swing.JScrollPane();
        taskManager = new swingExtended.todoQueue.TaskManager();
        tabbedPane = new javax.swing.JTabbedPane();
        addQueryPanel = new ngram_reader.viewer.AddQueryPanel();
        loadQueryPanel = new ngram_reader.viewer.LoadQueryPanel();
        progressPanel = new swingExtended.progressPanel.ProgressPanel();
        menuBar = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        menuItemSettings = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        javax.swing.GroupLayout taskManagerLayout = new javax.swing.GroupLayout(taskManager);
        taskManager.setLayout(taskManagerLayout);
        taskManagerLayout.setHorizontalGroup(
            taskManagerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 278, Short.MAX_VALUE)
        );
        taskManagerLayout.setVerticalGroup(
            taskManagerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 412, Short.MAX_VALUE)
        );

        scrollPaneStack.setViewportView(taskManager);

        tabbedPane.addTab("Add Query", addQueryPanel);
        tabbedPane.addTab("Load Query", loadQueryPanel);
        tabbedPane.addTab("Progress", progressPanel);

        jMenu1.setText("File");

        menuItemSettings.setText("Settings");
        menuItemSettings.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuItemSettingsActionPerformed(evt);
            }
        });
        jMenu1.add(menuItemSettings);

        menuBar.add(jMenu1);

        setJMenuBar(menuBar);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(tabbedPane, javax.swing.GroupLayout.PREFERRED_SIZE, 624, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(scrollPaneStack, javax.swing.GroupLayout.PREFERRED_SIZE, 280, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(tabbedPane, javax.swing.GroupLayout.DEFAULT_SIZE, 414, Short.MAX_VALUE)
            .addComponent(scrollPaneStack, javax.swing.GroupLayout.DEFAULT_SIZE, 414, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void menuItemSettingsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuItemSettingsActionPerformed
        this.SETTINGS_DIALOG.setVisible(true);
    }//GEN-LAST:event_menuItemSettingsActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private ngram_reader.viewer.AddQueryPanel addQueryPanel;
    private javax.swing.JMenu jMenu1;
    private ngram_reader.viewer.LoadQueryPanel loadQueryPanel;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JMenuItem menuItemSettings;
    private swingExtended.progressPanel.ProgressPanel progressPanel;
    private javax.swing.JScrollPane scrollPaneStack;
    private javax.swing.JTabbedPane tabbedPane;
    private swingExtended.todoQueue.TaskManager taskManager;
    // End of variables declaration//GEN-END:variables
}
